package com.gvsoft.communication.console;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:MService
 * Author: zhaoqiubo
 * Date: 15/11/11
 * Time: 上午8:54
 * Desc: 管理端口服务
 * 负责接收管理请求命令,并返回命令结果
 */
public class ControlListener extends Thread {
    private final static Logger logger = LogManager.getLogger("server");
    boolean flag = true;
    int consolePort = 9090;

    public ControlListener(String name,int port) {
        super(name);
        consolePort = port;
    }

    public void interrupt() {
        this.flag = false;
        super.interrupt();
    }

    public void run() {
        logger.info("control listener started at " + consolePort);
        try {
            ServerSocket listener = new ServerSocket(consolePort);
            try {
                while (flag) {
                    try {
                        Socket socket = listener.accept();
                        BufferedReader socketReader =
                                new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        String str = socketReader.readLine();
                        if (str == null) {
                            continue;
                        }
                        if (!str.equals("exit")) {
                            logger.info("accept control CMD: " + str);
                            String returnStr = Console.execute(str.trim());
                            socket.getOutputStream().write((returnStr + "\r\n#END#\r\n").getBytes());
                        } else {
                            socketReader.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        continue;
                    }
                }
                logger.info("control listener stoped");

            } finally {
                listener.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
